package com.business_clean.app.uitl;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.drawable.Drawable;
import android.text.TextUtils;
import android.util.Log;
import android.view.ViewGroup;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.afollestad.materialdialogs.MaterialDialog;
import com.blankj.utilcode.util.SizeUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.Transformation;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool;
import com.bumptech.glide.load.resource.bitmap.BitmapTransformation;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.CustomTarget;
import com.bumptech.glide.request.target.ImageViewTarget;
import com.bumptech.glide.request.target.Target;
import com.bumptech.glide.request.transition.Transition;
import com.business_clean.R;
import com.business_clean.app.callback.GetUrlCacheBitmapListenerWithFail;
import com.business_clean.app.ext.LoadingDialogExtKt;

import java.security.MessageDigest;

import me.hgj.mvvmhelper.ext.LogExtKt;

public class GlideUtil {


    public static void loadPicRound(Context context, String url, ImageView imageView, int degree) {
        if (context != null) {
            try {
                Glide.with(context).
                        load(url)
                        .diskCacheStrategy(DiskCacheStrategy.AUTOMATIC)
                        .placeholder(R.mipmap.icon_base_placeholder)
                        .thumbnail(0.2f)
                        .transform(new GlideRoundTransform((int) SizeUtils.dp2px(degree)))
                        .into(imageView);
            } catch (Exception ignored) {

            }
        } else {
            Log.i("Tag", "Picture loading failed,activity is null");
        }
    }


    public static void loadPicRound(Context context, String url, ImageView imageView, float thumbnail, int degree) {
        if (context != null) {
            try {
                Glide.with(context)
                        .load(url)
                        .thumbnail(thumbnail) // 缩略图的大小比例，可以根据需求调整
                        .diskCacheStrategy(DiskCacheStrategy.AUTOMATIC)
                        .placeholder(R.mipmap.icon_base_placeholder)
                        .thumbnail(0.2f)
                        .transform(new GlideRoundTransform((int) SizeUtils.dp2px(degree)))
                        .into(imageView);
            } catch (Exception ignored) {

            }
        } else {
            Log.i("Tag", "Picture loading failed,activity is null");
        }
    }

    public static void loadThumbnailImage(Context context, String imageUrl, ImageView imageView) {
        RequestOptions requestOptions = new RequestOptions()
                .diskCacheStrategy(DiskCacheStrategy.NONE) // 只缓存原始数据，即压缩图
                .override(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL) // 加载原始大小的图片
                .fitCenter();

        Glide.with(context)
                .asBitmap()
                .load(imageUrl)
                .thumbnail(0.1f) // 加载缩略图，0.1f表示缩略图大小为原图大小的1/10
                .transform(new GlideRoundTransform((int) SizeUtils.dp2px(4)))
                .apply(requestOptions)
                .into(new CustomTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                        int targetSize = 100; // 目标缩放尺寸
                        int width = resource.getWidth();
                        int height = resource.getHeight();

                        // 计算缩放比例
                        float scale = Math.min((float) targetSize / width, (float) targetSize / height);

                        // 创建Matrix对象并设置缩放比例
                        Matrix matrix = new Matrix();
                        matrix.postScale(scale, scale);

                        // 使用Matrix对原始图片进行缩放处理
                        Bitmap scaledBitmap = Bitmap.createBitmap(resource, 0, 0, width, height, matrix, true);

                        // 在ImageView中显示缩放后的图片
                        imageView.setImageBitmap(scaledBitmap);
                    }

                    @Override
                    public void onLoadCleared(@Nullable Drawable placeholder) {
                        // 清除加载
                    }
                });
    }


    public static void loadPic(Context context, String url, ImageView imageView) {
        if (context != null) {
            try {
                Glide.with(context).load(url)
                        .placeholder(R.mipmap.icon_base_placeholder)
                        .diskCacheStrategy(DiskCacheStrategy.AUTOMATIC)
                        .thumbnail(0.2f)
                        .dontAnimate()
                        .into(imageView);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * 聊天界面专用的 根据图片大小显示不同的布局
     *
     * @param context
     * @param url
     * @param imageView
     * @param placeholder
     * @param degree
     */
    public static void loadCirclePic(Context context, String url, ImageView imageView, int placeholder, int degree) {
        if (context != null) {
            try {
                Glide.with(context).load(url)
                        .placeholder(placeholder)
                        .diskCacheStrategy(DiskCacheStrategy.ALL)
                        .thumbnail(0.2f)
                        .transform(new GlideRoundTransform((int) SizeUtils.dp2px(degree)))
                        .dontAnimate()
                        .into(new CustomTarget<Drawable>() {
                            @Override
                            public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
                                //在这里计算 图片的长宽高 然后动态修改 ImageView 的大小
                                int width = resource.getIntrinsicWidth();
                                int height = resource.getIntrinsicHeight();
//                                LogExtKt.logE("图片的宽高+ " + width + " ; " + height, "");
                                ViewGroup.LayoutParams params = imageView.getLayoutParams();
                                //动态改变宽高
                                if (width >= 200) {
                                    // 动态修改 ImageView 的大小
                                    params.width = SizeUtils.dp2px(140);
                                    params.height = SizeUtils.dp2px(90);
                                } else {
                                    params.width = SizeUtils.dp2px(90);
                                    params.height = SizeUtils.dp2px(160);
                                }
                                imageView.setLayoutParams(params);
                                //设置图片
                                imageView.setImageDrawable(resource);
                            }

                            @Override
                            public void onLoadCleared(@Nullable Drawable placeholder) {

                            }
                        });
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static void getUrlCacheBitmapForShareThumbnail(final Activity activity, final String url, final GetUrlCacheBitmapListenerWithFail listner) {
        if (activity != null && !activity.isDestroyed()) {
            LogExtKt.logE("图片下载bitmap - " + url, "");
            if (!TextUtils.isEmpty(url)) {
                LoadingDialogExtKt.showLoadingExt((AppCompatActivity) activity, "图片下载中...");
                Glide.with(activity)
                        .asBitmap()
                        .load(url)
                        .diskCacheStrategy(DiskCacheStrategy.NONE)
                        .into(new CustomTarget<Bitmap>() {
                            @Override
                            public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                                LoadingDialogExtKt.dismissLoadingExt(activity);
                                if (listner != null) {
                                    listner.loadBitmap(resource);
                                }
                            }

                            @Override
                            public void onLoadCleared(@Nullable Drawable placeholder) {
                                LoadingDialogExtKt.dismissLoadingExt(activity);
                            }

                            @Override
                            public void onLoadFailed(@Nullable Drawable errorDrawable) {
                                super.onLoadFailed(errorDrawable);
                                LoadingDialogExtKt.dismissLoadingExt(activity);
                                if (listner != null) {
                                    listner.loadFail();
                                }
                            }
                        });
            } else {
                if (listner != null) {
                    listner.loadFail();
                }
            }
        } else {
            if (listner != null) {
                listner.loadFail();
            }
        }
    }

}
